package com.itheima.interceptor;

import com.itheima.util.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Slf4j
@Component
public class DemoInterceptor implements HandlerInterceptor {
    // ctrl + o: 实现方法
    // 拦截到了指定的请求, 放行前执行, return true: 放行, return false: 不放行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("DemoInterceptor preHandle 放行前: " + request.getRequestURL());

        // 获取请求头中的token
        String token = request.getHeader("token");
        System.out.println(token);
        // 判断token是否存在, 如果不存在, 返回401
        if (token == null) {
            log.error("如果不存在, 返回401!");
            response.setStatus(401);
            return false; // 不放行, return结束方法, 不执行后面代码
        }

        // 如果存在token, 解析token, 如果解析失败, 返回401
        try {
            JwtUtils.parseJWT(token);
        } catch (Exception e) {
            log.error("解析token失败, 返回401");
            response.setStatus(401);
            return false; // 不放行, return结束方法, 不执行后面代码
        }

        // 如果解析token成功, 放行
        log.info("解析token成功, 放行");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("DemoInterceptor postHandle 放行后");
    }
}
